import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

// 配置信息
const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue') // 路由懒加载
  },
  {
    path: '/news',
    component: () => import('../views/NewsView.vue')
  },
  {
    path: '/user',
    component: () => import('../views/UserView.vue'),
    children: [ // 子路由
      {
        path: 'login',
        component: () => import('../views/Login.vue')
      },
      {
        path: 'register/:name/:age/:sex',
        name: 'register',
        component: () => import('../views/Register.vue')
      }
    ]
  }
]

// 创建路由实例
const router = new VueRouter({
  routes,
  mode: 'history' // 路由模式
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  console.log(to)

  // 如果访问首页、登录页、注册页，则放行
  if(to.path == '/' || to.path == '/user/login' || to.name == 'register'){
    return next() // 放行
  }
  // 如果访问其他页面，判断是否登录
  if(localStorage.getItem('user')){
    return next() // 放行
  }
  // 如果没有登录，则跳转到登录页面
  next('/user/login')
})

export default router
